import 'package:auto_route/auto_route.dart';
import 'package:convergence_media/features/app/repository/app_config_repository.dart';
import 'package:convergence_media/features/user/repositories/token_repository.dart';
import 'package:convergence_media/navigator/app_router.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'auth_guard.g.dart';

@riverpod
AuthGuard authGuard(AuthGuardRef ref) => AuthGuard(
      tokenRepository: ref.watch(tokenRepositoryProvider),
      appConfigRepository: ref.watch(appConfigRepositoryProvider),
    );

class AuthGuard extends AutoRouteGuard {
  const AuthGuard({
    required AppConfigRepository appConfigRepository,
    required TokenRepository tokenRepository,
  })  : _appConfigRepository = appConfigRepository,
        _tokenRepository = tokenRepository;

  final TokenRepository _tokenRepository;
  final AppConfigRepository _appConfigRepository;

  @override
  Future<void> onNavigation(
    NavigationResolver resolver,
    StackRouter router,
  ) async {
    final currentHashId = _appConfigRepository.getCurrentHashId();
    if (currentHashId == null) {
      await router.push(const LoginRoute());
      return;
    }
    final isLogin = await _tokenRepository.isLogin(currentHashId);
    if (!isLogin) {
      // 如果没有登录就拦下来跳转到登录页
      await router.push(const LoginRoute());
    } else {
      // 否则允许继续访问个人页
      resolver.next(isLogin);
    }
  }
}
